<template>
  <div class="resume-list-container">
    <!-- 标题区域 -->
    <div class="list-header">
      <h2 class="list-title">{{ $t('resume.myResumes') }}</h2>
      <el-button 
        type="primary" 
        @click="createNewResume"
        class="create-btn"
      >
        <el-icon><Plus /></el-icon>
        {{ $t('resume.createNewResume') }}
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 简历列表 -->
    <div v-else-if="resumeList.length > 0" class="resume-list">
      <div 
        v-for="(resume, index) in resumeList" 
        :key="index"
        class="resume-item"
        @click="selectResume(resume)"
      >
        <div class="resume-info">
          <div class="resume-title">
            <h3>{{ resume.title || $t('resume.myResumes') }}</h3>
          </div>
          <div class="resume-details">
            <span class="resume-date">{{ $t('resume.createTime') }} {{ formatDate(resume.createdAt) }}</span>
            <!-- 调试信息：显示原始状态值 -->
            <span v-if="!getResumeStatus(resume)" class="debug-info" style="color: #999; font-size: 12px;">
              状态: 未设置
            </span>
            <el-tag 
              :type="getStatusType(getResumeStatus(resume))" 
              size="small"
              class="status-tag"
            >
              {{ getStatusText(getResumeStatus(resume)) }}
            </el-tag>
            <!-- 调试信息：显示原始状态字段值 -->
            <!-- <span class="debug-info" style="color: #999; font-size: 10px; margin-left: 8px;">
              ({{ JSON.stringify({resumeStatus: resume.resumeStatus, status: resume.status}) }})
            </span> -->
          </div>
        </div>
        <div class="resume-actions">
          <el-button 
            plain
            size="small"
            @click.stop="editResume(resume)"
            class="edit-btn"
          >
            {{ $t('resume.edit') }}
          </el-button>
          <el-button 
            type="danger" 
            size="small"
            @click.stop="deleteResume(resume)"
          >
            {{ $t('resume.delete') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">
        <el-icon size="64"><Document /></el-icon>
      </div>
      <h3 class="empty-title">{{ $t('resume.noResumeYet') }}</h3>
      <p class="empty-description">{{ $t('resume.noResumeDescription') }}</p>
      <el-button 
        type="primary" 
        size="large"
        @click="createNewResume"
        class="create-first-btn"
      >
        <el-icon><Plus /></el-icon>
        {{ $t('resume.createFirstResume') }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Document } from '@element-plus/icons-vue'
import { studentApi } from '../../api/index.js'
import { useI18n } from 'vue-i18n'

// 使用i18n
const { t } = useI18n()

// 定义事件
const emit = defineEmits(['select-resume', 'create-resume'])

// 响应式数据
const loading = ref(false)
const resumeList = ref([])

// 获取简历列表
const fetchResumeList = async () => {
  try {
    loading.value = true
    const response = await studentApi.getResume()
    
    if (response.code === 200) {
      if (response.data && Array.isArray(response.data)) {
        resumeList.value = response.data
        // 调试信息：查看简历数据结构
        console.log('简历列表数据:', response.data)
        response.data.forEach((resume, index) => {
          console.log(`简历 ${index + 1}:`, {
            id: resume.id,
            resumeStatus: resume.resumeStatus,
            status: resume.status,
            title: resume.title
          })
        })
      } else if (response.data && typeof response.data === 'object') {
        // 如果返回的是单个简历对象，转换为数组
        resumeList.value = [response.data]
        // 调试信息：查看单个简历数据结构
        console.log('单个简历数据:', response.data)
        console.log('简历状态字段:', {
          resumeStatus: response.data.resumeStatus,
          status: response.data.status
        })
      } else {
        resumeList.value = []
      }
    } else {
      console.warn('获取简历列表失败:', response.message)
      resumeList.value = []
    }
  } catch (error) {
    console.error('获取简历列表异常:', error)
    resumeList.value = []
  } finally {
    loading.value = false
  }
}

// 选择简历
const selectResume = (resume) => {
  emit('select-resume', resume)
}

// 创建新简历
const createNewResume = () => {
  emit('create-resume')
}

// 编辑简历
const editResume = (resume) => {
  emit('select-resume', resume)
}

// 删除简历
const deleteResume = async (resume) => {
  try {
    await ElMessageBox.confirm(
      t('resume.confirmDelete'),
      t('common.warning'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }
    )
    
    const response = await studentApi.deleteResume(resume.id)
    
    if (response.code === 200) {
      ElMessage.success(t('resume.deleteSuccess'))
      await fetchResumeList()
    } else {
      ElMessage.error(response.message || t('resume.deleteFailed'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除简历失败:', error)
      ElMessage.error(t('resume.deleteFailed'))
    }
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN')
  } catch (error) {
    return dateString
  }
}

// 获取简历状态 (优先使用 resumeStatus，如果没有则使用 status)
const getResumeStatus = (resume) => {
  if (!resume) return null
  
  // 调试信息
  console.log('简历状态字段详情:', {
    resumeStatus: resume.resumeStatus,
    status: resume.status,
    resumeStatusType: typeof resume.resumeStatus,
    statusType: typeof resume.status
  })
  
  // 如果resumeStatus存在且是字符串
  if (resume.resumeStatus && typeof resume.resumeStatus === 'string') {
    return resume.resumeStatus
  }
  
  // 如果status存在且是字符串
  if (resume.status && typeof resume.status === 'string') {
    return resume.status
  }
  
  // 如果resumeStatus是对象，尝试获取其中的状态值
  if (resume.resumeStatus && typeof resume.resumeStatus === 'object') {
    if (resume.resumeStatus.status) {
      return resume.resumeStatus.status
    }
    if (resume.resumeStatus.value) {
      return resume.resumeStatus.value
    }
    if (resume.resumeStatus.name) {
      return resume.resumeStatus.name
    }
  }
  
  // 如果status是对象，尝试获取其中的状态值
  if (resume.status && typeof resume.status === 'object') {
    if (resume.status.status) {
      return resume.status.status
    }
    if (resume.status.value) {
      return resume.status.value
    }
    if (resume.status.name) {
      return resume.status.name
    }
  }
  
  // 如果都没有找到有效的状态值，返回null
  return null
}

// 获取状态类型
const getStatusType = (status) => {
  // 处理空值或未定义的情况
  if (!status || status === '' || status === null) return 'info'
  
  const typeMap = {
    pending: 'warning',
    pending_review: 'warning',
    approved: 'success',
    rejected: 'danger',
    incomplete: 'info',
    draft: 'info',
    submitted: 'warning',
    reviewing: 'warning',
    active: 'success',
    inactive: 'info',
    expired: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  // 处理空值或未定义的情况
  if (!status || status === '' || status === null) return t('resume.statusDraft')
  
  const textMap = {
    pending: t('resume.statusPending'),
    pending_review: t('resume.statusPending'),
    approved: t('resume.statusApproved'),
    rejected: t('resume.statusRejected'),
    incomplete: t('resume.statusIncomplete'),
    draft: t('resume.statusDraft'),
    submitted: t('resume.statusSubmitted'),
    reviewing: t('resume.statusReviewing'),
    active: t('resume.statusActive'),
    inactive: t('resume.statusInactive'),
    expired: t('resume.statusExpired')
  }
  return textMap[status] || t('resume.unknownStatus')
}

// 组件挂载时获取简历列表
onMounted(() => {
  fetchResumeList()
})
</script>

<style scoped>
.resume-list-container {
  padding: 30px;
  background: #fff;
  height: 100%;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.list-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.create-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.loading-container {
  padding: 40px 0;
}

.resume-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.resume-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px;
  border: 1px solid #e8e8e8;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.resume-item:hover {
  border-color: #409eff;
  background: #f8f9ff;
}

.resume-info {
  flex: 1;
}

.resume-title {
  margin-bottom: 12px;
}

.resume-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}



.resume-details {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #666;
  font-size: 14px;
}

.resume-date {
  color: #666;
}

.status-tag {
  font-size: 12px;
}

.resume-actions {
  display: flex;
  gap: 12px;
}

.edit-btn {
  color: #666;
  border-color: #dcdfe6;
}

.edit-btn:hover {
  color: #409eff;
  border-color: #409eff;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
}

.empty-icon {
  color: #c0c4cc;
  margin-bottom: 24px;
}

.empty-title {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.empty-description {
  margin: 0 0 32px 0;
  color: #666;
  font-size: 16px;
}

.create-first-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0 auto;
  font-weight: 500;
}
</style> 